package com.stand.hardcode.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.KeyFactory;
import com.stand.hardcode.entity.StandUser;
import com.stand.hardcode.manager.UserManager;
import com.stand.hardcode.util.ParamsVerifier;
import com.stand.hardcode.util.RequestAttributes;

public class AdminGrantServlet extends HttpServlet{

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		if(UserManager.IsLoggedIn(req)){
			System.out.println("logged in");
			StandUser u =(StandUser)req.getSession().getAttribute(RequestAttributes.CURRENT_USER);
			if(u.isAdmin()){
				System.out.println("is admin");
				String email = req.getParameter(RequestAttributes.SEARCH_EMAIL);
				if(ParamsVerifier.ParamsNotNull(email)){
					System.out.println("not null");
					StandUser s = UserManager.RetrieveUser(KeyFactory.createKey(StandUser.class.getSimpleName(), email));
					if(s != null){
						s.setAdmin(true);
						UserManager.UpdateUser(s);
						req.setAttribute(RequestAttributes.ADMIN_GRANTED, "admin rights granted to "+email);
						try {
							req.getRequestDispatcher("adminpanel.jsp").forward(req, resp);
						} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}else{
						req.setAttribute(RequestAttributes.ADMIN_GRANTED, "no such account");
						try {
							req.getRequestDispatcher("/adminpanel.jsp").forward(req, resp);
						} catch (ServletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
		
		
	}
					
				
	
	

}
